/**
 * 
 */
package com.scpii.universal.pns.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import org.hibernate.Hibernate;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import com.scpii.universal.constant.GenericConstants;
import com.scpii.universal.hibernate.dao.impl.BaseDaoImpl;
import com.scpii.universal.pns.dao.TagValuesDao;
import com.scpii.universal.pns.entity.TagValues;

/**
 * genericWeb
 * 
 * @author acer 2012-7-5下午04:35:11
 */
@Repository
public class TagValuesImpl extends BaseDaoImpl<TagValues, Long> implements
		TagValuesDao {

	@Override
	public void deleteByTagId(Long tagId) {
		String hql = "delete from TagValues t where t.tagId=?";
		getHibernateTemplate().getSessionFactory().getCurrentSession()
				.createQuery(hql).setParameter(0, tagId).executeUpdate();
	}

	@Override
	public void deleteByTargetId(Long targetId) {
		String hql = "delete from TagValues t where t.targetId=?";
		getHibernateTemplate().getSessionFactory().getCurrentSession()
				.createQuery(hql).setParameter(0, targetId).executeUpdate();
	}

	@Override
	public Map<String, String> getTagIdsByTargetId(String targetIds) {
		ResourceBundle bundle = ResourceBundle.getBundle(GenericConstants.GLOBAL_PROPERTIES_PATH, Locale.getDefault());
		String pnsSchema = bundle.getString("pns.schema");
		String sql = "select t1.target_id as id,wmsys.wm_concat(t1.tag_id) as ids from "+pnsSchema+".tag_values t1 "
				+ "where t1.target_id in("+targetIds+") group by t1.target_id";
		@SuppressWarnings("unchecked")
		List<Map<String,Object>> results = getHibernateTemplate().getSessionFactory().getCurrentSession()
				.createSQLQuery(sql).addScalar("ID", Hibernate.LONG).addScalar("IDS", Hibernate.STRING).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
		Map<String,String> data = new HashMap<String,String>();
		for (Map<String, Object> map : results) {
			data.put(map.get("ID").toString(), map.get("IDS").toString());
		}
		return data;
	}

}
